package com.mgkj.controller.WMS;



import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.mgkj.annotation.Log;
import com.mgkj.base.HttpResult;
import com.mgkj.common.result.Result;
import com.mgkj.common.utils.HttpClientUtil;
import com.mgkj.dto.*;
import com.mgkj.dto.yf.InitJhdDto;
import com.mgkj.dto.yf.InitPURTHDto;
import com.mgkj.dto.yf.InitThdDto;
import com.mgkj.entity.Invmb;
import com.mgkj.entity.ShenHe;
import com.mgkj.mapper.*;
import com.mgkj.service.*;
import com.mgkj.vo.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author yyyjcg
 * @date 2023/12/26
 * @Description
 */
@Slf4j
@RestController
@Api(tags = "采购管理相关接口")
@RequestMapping("/api/Purchase")

public class PurchaseController {
    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private PurchaseTwoService purchaseTwoService;

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private WeChatService weChatService;

    @Autowired
    private InvBarcodeOperationMapper invBarcodeOperationMapper;

    @Autowired
    private PurchaseSummaryService purchaseSummaryService;

    @Autowired
    private PurchaseSummaryMapper purchaseSummaryMapper;

    @Autowired
    private DeliverySummaryService deliverySummaryService;
    @Autowired
    private DeliverySummaryMapper deliverySummaryMapper;

    @Autowired
    private EnterStorageService enterStorageService;

    @Resource
    private EnterStorageMapper enterStorageMapper;
    @Resource
    private CommonService commonService;
    @Resource
    private InvmbMapper invmbMapper;

        @ApiOperation("到货检验-获取满足检验的到货单")
        @Log("获取满足检验的到货单")
//        @PostMapping("/ListPurchaseArrivalStorageWaitCheck")
        public Result<PageInfo<PurchaseArrivalCheckHeader>> ListPurchaseArrivalStorageWaitCheck(@RequestBody PurchaseArrivalStorageWaitCheckDto dto){
            return purchaseService.ListPurchaseArrivalStorageWaitCheck(dto);
        }

        @Log("到货检验-->批量生成到货检验单")
        @ApiOperation("批量生成到货检验单")
        @PostMapping("/UpdatePurchaseArrivalStorageCheck")
        public Result UpdatePurchaseArrivalStorageCheck(@RequestBody PurchaseArrivalCheck dto){
            List<InspectDto> inspectDtos = new ArrayList<>();
            for (PurchaseArrivalCheckHeader header : dto.getHeader()) {

                String[] split = header.getArrivalDocNo().split("-");
                if (split.length != 2) {
                    return Result.fail().message("到货单单号格式不正确：" + header.getArrivalDocNo());
                }
                String dhdb = split[0]; //
                String dhdh = split[1]; //
                String xh = header.getArrivalDSequenceNumber();

                InspectDto inspectDto = new InspectDto();
                inspectDto.setCreator(header.getCreateBy());
                inspectDto.setDhdb(dhdb);
                inspectDto.setDhdh(dhdh);
                inspectDto.setXh(xh);
                inspectDto.setAccNumber(header.getAccNumber());
                inspectDto.setReturnNumber(header.getReturnNumber());
                inspectDto.setScrapNumber(header.getScrapNumber());
                inspectDto.setBreakNumber(header.getBreakNumber());
                inspectDto.setArrivePackageNumber(header.getArrivePackageNumber());
                inspectDto.setAccPackageNumber(header.getAccPackageNumber());
                inspectDto.setReturnPackageNumber(header.getReturnPackageNumber());
                inspectDto.setScrapPackageNumber(header.getScrapPackageNumber());
                inspectDto.setBreakPackageNumber(header.getBreakPackageNumber());
                inspectDtos.add(inspectDto);
            }

            Map<String, String> flag = enterStorageService.arrivalInvoiceBatch(inspectDtos);
            return Result.ok(flag);

//            return purchaseService.UpdatePurchaseArrivalStorageCheck(dto);
        }

    @ApiOperation("批量生成到货检验单")
    @Log("批量生成到货检验单")
    @PostMapping("/PurchaseReceiptStorage")
    @Transactional
    public Result PurchaseReceiptStorage(@RequestBody PurchaseReceiptDto Dto) {
        List<InspectDto> inspectDtos = new ArrayList<>();
        for (PurchaseReceiptStorageDto dto : Dto.getList()) {

            String[] split = dto.getDocNo().split("-");
            if (split.length != 2) {
                return Result.fail().message("到货单单号格式不正确：" + dto.getDocNo());
            }
            String dhdb = split[0]; //
            String dhdh = split[1]; //
            dto.getXh();

            InspectDto inspectDto = new InspectDto();
            inspectDto.setCreator(dto.getCreator());
            inspectDto.setDhdb(dhdb);
            inspectDto.setDhdh(dhdh);
            inspectDto.setXh(dto.getXh());
            inspectDto.setAccNumber(dto.getMatchQty());
            inspectDto.setReturnNumber(dto.getReturnQty());
            inspectDto.setScrapNumber(dto.getScrapQty());
            inspectDto.setBreakNumber(dto.getBreakQty());
            inspectDtos.add(inspectDto);
        }

        Map<String, String> flag = enterStorageService.arrivalInvoiceBatch(inspectDtos);
        return Result.ok(flag);
    }


    @ApiOperation("获取满足检验的到货单")
//    @Log("获取满足检验的到货单")
    @PostMapping("/getPurcharseDeliveryNo")
    public Result<PageInfo<PurchaseReceiptStorageVo>> getPurcharsedeliveryNo(@RequestBody PurcharseDeliveryDto dto) {
        //查获取满足检验的到货单数据
        if (dto == null ) {
            return Result.<PageInfo<PurchaseReceiptStorageVo>>fail().message("参数不能为空！");
        }
        PageHelper.startPage(dto.getPage(), dto.getSize());
        List<PurchaseReceiptStorageVo> purcharsedeliveryNo = purchaseMapper.getNeedInspect();
        PageInfo<PurchaseReceiptStorageVo> pageInfo = new PageInfo<>(purcharsedeliveryNo);

        return Result.ok(pageInfo);
    }

    @ApiOperation(("获取满足入库的到货检验单客户"))
    @PostMapping("/needArrivalInsCustomer")
    public Result<List<NeedArrivalInsVo>> needArrivalInsCustomer(){
        return Result.ok(enterStorageService.needArrivalInsCustomer());
    }

    @ApiOperation("获取满足入库的到货检验单")
    @PostMapping("/getNeedArrivalIns")
    @Log("获取满足入库的到货检验单")
    public Result<PageInfo<NeedArrivalInsVo>> getInspect(@RequestBody NeedArrivalInsDto needArrivalInsDto){
        if (needArrivalInsDto  == null) {
            return Result.<PageInfo<NeedArrivalInsVo>>fail().message("参数不能为空！");
        }
        return Result.ok(enterStorageService.getNeedArrivalIns(needArrivalInsDto));
    }


    @GetMapping("/getsuppliersvo")
    @ApiOperation(("获取符合进货单到到货单的供应商"))
    public Result<List<SupplierVo>> selecttt () {
        return Result.ok(enterStorageMapper.selecttt());
    }

    @PostMapping("/insertjhdByArrBatch")
    @ApiOperation("产生进货单")
    @Log("批量生成进货单")
    public Result insertjhdBatch(@RequestBody InitJhdDto jhdDtos) throws UnknownHostException {
        //进货单单号后端产生，并组装dto去调用易飞接口

        String TG001 = "3410";
        String TG002 = commonService.getIdByType(TG001,  "PURTG"); // 入库单号
        String TG003 = new SimpleDateFormat("yyyyMMdd").format(new Date());
        jhdDtos.setTG001(TG001);
        jhdDtos.setTG002(TG002);
        jhdDtos.setTG003(TG003);
        jhdDtos.setTG004("1000");
        jhdDtos.setCompany("ZJQH");
        jhdDtos.setTG013("N");
        List<InitPURTHDto> purthList = jhdDtos.getInitPurthDtoList();
        if (purthList == null && purthList.isEmpty()) {
            return Result.fail().message("进货单身不能为空！");
        }
            for (int i = 0; i < purthList.size(); i++) {

                InitPURTHDto purthDto = purthList.get(i);
                //对其每个品号进行判断，开启批号管理则批号是TD021，否则是“*”
                Invmb invmb = invmbMapper.selectOne(new QueryWrapper<Invmb>().eq("MB001",purthDto.getTH004()));

                if(!invmb.getMb022().trim().equals("N")){
                    String lotCode = purchaseMapper.selectLotCode(purthDto.getTH011(),purthDto.getTH012(),purthDto.getTH013());
                    purthDto.setTH010(lotCode);
                }else{
                    purthDto.setTH010("********************");

                }
                purthDto.setTH001(TG001);
                purthDto.setTH002(TG002);
                int sequence = i + 1;
                String th003 = String.format("%04d", sequence);
                purthDto.setTH003(th003);
                //计价数量=验收数量
                purthDto.setTH016(purthDto.getTH015());
                purthDto.setTH014(TG003);
                purthDto.setTH072(purthDto.getTH072());

            }

        Result result = enterStorageService.insertjhdBatch(jhdDtos);
        if (result.getCode() != 200) {
//                return Result.fail().message("生成生产入库单失败，入库单号：" + TF001 + '-' + TF002 + result.getData());
            return Result.fail().message("生成采购进货单，进货单号：" + TG001 + '-' + TG002 + result.getMessage());
        }
        return Result.ok("生成采购进货单，进货单号：" + TG001 + '-' + TG002 + "成功！").message("成功");

    }

    @GetMapping("/audit")
    @ApiOperation("审核测试")
    public Result test1() throws UnknownHostException {

        ShenHe shenHe = new ShenHe();
        shenHe.setCom("ZJQH");
        shenHe.setProgram("PURI09");
        shenHe.setUser("DS");
        shenHe.setDb("3410");
        shenHe.setDh("20250807001");
        shenHe.setType("DO");
        shenHe.setRq("20250807");

//        InetAddress localhost = InetAddress.getLocalHost();
//        String ipAddress = localhost.getHostAddress();
//        String url = "http://" + ipAddress + ":9000/api/yifei/audit";
        String url = "http://" + "192.168.0.141" + ":9000/api/yifei/audit";


        String jsonString = JSON.toJSONString(shenHe);
        String ans = null;
        try {
//            ShenHe anss=restTemplate.postForObject(url,shenHe,ShenHe.class);
            ans = HttpClientUtil.postRequest(url, jsonString);
        } catch (Exception e) {

            return Result.fail("出现异常请查看审批后台是否开启");
        }
        HttpResult httpResult = new HttpResult();

        if (ans == null) {
            return Result.fail("出现异常请查看审批后台是否开启");
        } else {
            httpResult = JSON.parseObject(ans, HttpResult.class);
//            System.out.println("httpResult: " + httpResult);
        }
        if (httpResult.getStatus().equals("失败")) {

            return Result.fail(httpResult.getReason() + httpResult.getDetail());
        }
        System.out.println("审批结果：" + httpResult.getReason() + httpResult.getDetail());
        return null;
    }

    @PostMapping("/insertBackByArrBatch")
    @ApiOperation("产生退货单")
    public Result insertBackByArrBatch(@RequestBody InitThdDto initThdDto) throws UnknownHostException {
        Result result = enterStorageService.insertBackByArrBatch(initThdDto);
        return result;
    }



}
